import NProgress from 'nprogress'
import { useAuthStore, useAppStore } from '@/store'
import defaultSettings from '@/settings'

import { generateDynamicRoutes, resetRouter } from '@/router'

import type { Router } from 'vue-router'

const { routerWhiteList } = defaultSettings
export function setupRouterPermission(router: Router) {
	NProgress.start()

	router.beforeEach(async (to, from) => {
		const appStore = useAppStore()
		const authStore = useAuthStore()
		const title = import.meta.env.VITE_APP_TITLE
		document.title = to.meta.title ? `${to.meta.title} - ${title}` : title
		// console.log('router：', to.matched, from.fullPath, router.getRoutes())

		if (to.path === '/login') {
			if (appStore.token) return false
			resetRouter()
			return true
		}
		if (routerWhiteList.includes(to.path)) return true
		if (!appStore.token) return { path: '/login', replace: true }
		// // 如果没有菜单列表，就重新请求菜单列表并添加动态路由
		if (!authStore.menuList.length) {
			await generateDynamicRoutes()
			return { ...to, replace: true }
		}
	})
	router.onError((error) => {
		NProgress.done()
		console.warn('路由错误：', error.message)
	})
	router.afterEach(() => {
		NProgress.done()
	})
}
